package detect.parse.tree.token;

import java.util.List;
import java.util.regex.*;


public class TokenList {
	
	public PositionString psStr=null;
	public List<Token> tokens=null;
	public String tokensStr=null;	
	
	@Override
	public String toString(){
		return psStr.str;
	}
	
	public TokenList(PositionString _rawStr,List<Token> _tokens){
		psStr=_rawStr;
		tokens=_tokens;
		char[] typeChars=new char[tokens.size()];
		for(int i=0;i<tokens.size();i++){
			typeChars[i]=tokens.get(i).rawType.typeChar;
		}
		tokensStr=new String(typeChars);
	}
	
	public TokenList subList(int fromTokenIndex,int toTokenIndex){
		int fromStrIndex=tokens.get(fromTokenIndex).beginPosition;
		Token endToken=tokens.get(toTokenIndex-1);
		int toStrIndex=endToken.beginPosition+endToken.str.length();
		return new TokenList(psStr.subRelatedString(fromStrIndex-psStr.beginPosition,toStrIndex-psStr.beginPosition),
							 tokens.subList(fromTokenIndex, toTokenIndex));
	}
	public TokenList subList(int fromTokenIndex){
		return subList(fromTokenIndex,tokens.size());
	}
	
	public int size(){
		return tokens.size();
	}
	
	public Token get(int index){
		return tokens.get(index);
	}
	
	public Token getLast(){
		return tokens.get(tokens.size()-1);
	}
	
	public boolean contains(RawTokenType type){
		return tokensStr.contains(type.typeChar+"");
	}
	
	public int indexOf(RawTokenType type){
		return indexOf(type,0);
	}
	
	public int indexOf(RawTokenType type,int fromIndex){
		return tokensStr.indexOf(type.typeChar,fromIndex);
	}
	
	public int indexOf(String regex,int fromIndex){
		return tokensStr.indexOf(regex,fromIndex);
	}
	
	public int findMatchRightBrace(int leftBraceIndex,RawTokenType leftBraceType,RawTokenType rightBraceType){		
		int leftBraceCount=1;
		for(int i=leftBraceIndex+1;i<tokensStr.length();i++){
			RawTokenType type=tokens.get(i).rawType;
			if(type==leftBraceType){
				leftBraceCount++;
			}			
			else if(type==rightBraceType){
				leftBraceCount--;
				if(leftBraceCount==0){
					return i;
				}
			}
		}
		
		return -1;
	}
	
	public int lastIndexOf(RawTokenType type){
		return lastIndexOf(type,0);
	}
	
	public int lastIndexOf(RawTokenType type,int fromIndex){
		return tokensStr.lastIndexOf(type.typeChar,fromIndex);
	}
	
	public TokenList matchOnce(String regex,int fromIndex,int groupId){
		Pattern p=Pattern.compile(regex);
		Matcher m=p.matcher(tokensStr);
		if(m.find()){
			int start=m.start(groupId);
			int end=m.end(groupId);			
			return this.subList(start, end);
		}
		return null;
	}
}
